package org.canaan.spring.resolver;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;

/**
 @Author Canaan
 @Date 2017/11/13 */
public class DateConverter implements Converter<String, Date> {
    private final Logger logger = LoggerFactory.getLogger(DateConverter.class);

    private String[] patterns = new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm"};

    @Override
    public Date convert(String s) {
        if(StringUtils.isBlank(s)){return null; }
        try {
            return DateUtils.parseDate(s, patterns);
        } catch (ParseException e) {
            String url = null;
            try {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                if (request != null) {
                    url = request.getRequestURL().toString();
                }
            } catch (Exception e1) {
                url = "";
            }
            logger.error("时间格式化出错:{} -- {}", s, url);
        }
        return null;
    }

    /**
     默认解析："yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm"
     @param patterns
     */
    public void setPatterns(String[] patterns) {
        this.patterns = patterns;
    }
}
